/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.commons.marshaller.decls;

import org.geoscheduler.commons.marshaller.JSONField;
import org.geoscheduler.commons.marshaller.JSONFieldDecl;
import org.geoscheduler.commons.marshaller.JSONFieldDeclFactory;
import org.geoscheduler.commons.tools.PropertyDescriptor;
import org.geoscheduler.commons.tools.StringTools;

/**
 * 
 * <h2>JSONAbstractFieldDecl</h2>
 * <p>
 * Abstract superclass for implementing {@link JSONFieldDecl} types.
 * </p>
 * 
 * @author lko
 */
public abstract class JSONAbstractFieldDecl<T> implements JSONFieldDecl<T> {

	private PropertyDescriptor<T> desc;
	private T defValue;
	private String name;
	private String jsonName;
	private JSONField annotation;

	protected JSONAbstractFieldDecl(PropertyDescriptor<T> desc) {
		this(desc, null);
	}

	protected JSONAbstractFieldDecl(PropertyDescriptor<T> desc, T defValue) {
		this.desc = desc;
		this.defValue = defValue;
		this.name = desc.getName();
		this.annotation = desc.getAnnotation(JSONField.class);
		this.jsonName = StringTools.isEmptyTrimmed(annotation.value()) ? this.name : annotation.value();
	}

	protected PropertyDescriptor<T> getDescriptor() {
		return desc;
	}

	public String getName() {
		return name;
	}

	public String getJSONName() {
		return jsonName;
	}

	public Class<T> getType() {
		return desc.getType();
	}

	public T getDefaultValue() {
		return this.defValue;
	}

	protected void setDefaultValue(T value) {
		this.defValue = value;
	}

	protected JSONField getAnnotation() {
		return this.annotation;
	}

	protected String evalDefaultValue(PropertyDescriptor<?> desc) {
		return evalDefaultValue(desc.getAnnotation(JSONField.class));
	}

	protected String evalDefaultValue(JSONField annotation) {
		String defValue = null;
		if (!annotation.Null()) {
			defValue = annotation.value();
		}
		return defValue;
	}

	protected abstract static class BaseAbstractFactory<T> implements JSONFieldDeclFactory<T> {

		public boolean isApplicable(PropertyDescriptor<?> desc) {
			return desc.getAnnotation(JSONField.class) != null;
		}

	}
}
